/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.common.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

/**
 * This is {@link CAFJSONBinding}.
 *
 * @author yisiqi
 * @since 1.0.0
 */
@SuppressWarnings("unused")
@Deprecated
public class CAFJSONBinding<T> extends SimpleModule {


    private CAFJSONBinding(Class<T> type) {
        super(type.getCanonicalName());
    }

    public CAFJSONBinding(Class<T> type, CAFJSONSerializer<T> serializer, CAFJSONDeserializer<T> deserializer) {
        this(type);
        if (serializer != null) {
            this.addSerializer(type, new SerializerWrapper(type, serializer));
        }
        if (deserializer != null) {
            this.addDeserializer(type, new DeserializerWrapper(type, deserializer));
        }
    }

    public CAFJSONBinding(Class<T> type, CAFJSONSerializer<T> serializer) {
        this(type, serializer, null);
    }

    public CAFJSONBinding(Class<T> type, CAFJSONDeserializer<T> deserializer) {
        this(type, null, deserializer);
    }


    private class SerializerWrapper extends StdSerializer<T> {

        private final CAFJSONSerializer<T> serializer;

        private SerializerWrapper(Class<T> type, CAFJSONSerializer<T> serializer) {
            super(type);
            this.serializer = serializer;
        }

        @Override
        public void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            serializer.serialize(value, gen, provider);
        }
    }

    private class DeserializerWrapper extends StdDeserializer<T> {

        private final CAFJSONDeserializer<T> deserializer;

        private DeserializerWrapper(Class<T> type, CAFJSONDeserializer<T> deserializer) {
            super(type);
            this.deserializer = deserializer;
        }

        @Override
        public T deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
            return deserializer.deserialize(p, ctx);
        }
    }
}
